package com.learn.sunday.stock;

import lombok.extern.slf4j.Slf4j;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;

/**
 * 测试数据库分布式锁，此处使用多线程模拟多进程
 */
@Slf4j
public class Test3 {

    private static String driverName = "com.mysql.jdbc.Driver";
    private static String username = "root";//数据库登录名
    private static String password = "Admin123!";//密码
    private static String sql = "select * from t where id = 1 for update";
    private static String url = "jdbc:mysql://localhost:3306/data?useUnicode=true&characterEncoding=gbk&useSSL=false";

    public static void main(String[] args) {


        try { // 加载数据库驱动类
            Class.forName(driverName);
            log.info("数据库驱动加载成功");
        } catch (ClassNotFoundException e) {
            log.error("Load jdbc driver:{} ex:", driverName, e);
        }
        for (int i = 0; i < 2; i++) {
            new Thread(() -> {
                while (true) {

                    boolean connAutoCommit = false;
                    log.info("Start...");
                    Connection conn = getConn();
                    if (conn != null) {
                        try {
                            connAutoCommit = conn.getAutoCommit();
                            conn.setAutoCommit(false);
                            PreparedStatement preparedStatement = conn.prepareStatement(sql);
                            preparedStatement.setQueryTimeout(0);
                            preparedStatement.execute();
                            Thread.sleep(300000L);
                            log.info("处理完成");
                        } catch (SQLException e) {
                            log.error("Execute sql:{} ex", e);
                        } catch (InterruptedException e) {
                            log.error("Execute sql:{} Interrupted", e);
                        } finally {
                            try {
                                conn.commit();
                                conn.setAutoCommit(connAutoCommit);
                            } catch (SQLException e) {
                                log.error("Execute commit ex", e);
                            }
                        }
                    }
                    log.info("End...");
                }

            }, "test" + i).start();
        }


    }


    public static Connection getConn() {

        try { // 通过访问数据库的URL获取数据库连接对象
            Connection con = DriverManager.getConnection(url, username, password);
            return con;
        } catch (SQLException e) {
            log.error("Create jdbc conn ex:", e);
        }
        return null;
    }
}
